import Taro from "@tarojs/taro";

// API地址 http://command.trinasolar.com
// 文件地址 http://command.trinasolar.com/public


// 测试地址
// export const baseUrl = `http://42.192.227.252:8080/`

// export const baseUrl = 'https://api.yzthunder.cn/'
export const baseUrl = 'https://api.fanqiushuhua.com/'
// export const baseImageUrl = `https://riverecho.cn/solar/public`

// export const baseUrl = `http://command.trinasolar.com/api`
// export const baseImageUrl = `http://command.trinasolar.com/public`

// export const generateImageUrl = (uuid: string, ext: string) => {
//   return `${baseImageUrl}/${uuid}.${ext}`
// }

const request = (
  url: string,
  options: {
    method: Taro.request.Option["method"];
    data: Taro.request.Option["data"];
  },
  isFormData?: boolean,
  _needTimeOut?: boolean
) => {
  return new Promise((resolve, reject) => {
    const token = Taro.getStorageSync("token");
    Taro.request({
      url: baseUrl + url,
      method: options.method,
      data: options.data,
      timeout: 180000,
      header: {
        "content-type": isFormData
          ? "application/x-www-form-urlencoded"
          : "application/json;charset=UTF-8",
        // Authorization: token,
        token: token
        // cookie: "JSESSIONID=15302B1F20D0992172E9B26231DDDCA9"
      },
      success(res) {
        Taro.hideLoading()
        if (res.data.code === 601) {
          Taro.navigateTo({
            url: '/packages/package-login/index'
          })
          return false
        }
        if (res.data.errno == 404 || res.data.errno == 610 || res.data.errno == 601 || res.data.errno == 602 || res.data.errno == 603) {
          Taro.showToast({
            title: res.data.errmsg,
            icon: 'none'
          })
          resolve(false)
        }
        // put post 请求 没有data返回
        if (res.data.errno == 0 && !res.data.data) {
          resolve(true)
        }
        resolve(res.data.data);
      },
      fail(error) {
        reject(error);
      }
    }).catch(_e => { });
  }).catch(_e => { });
};

const originRequest = (
  url: string,
  options: {
    method: Taro.request.Option["method"];
    data: Taro.request.Option["data"];
  },
  isFormData?: boolean
) => {
  return new Promise((resolve, reject) => {
    const token = Taro.getStorageSync("token");
    Taro.request({
      url: baseUrl + url,
      method: options.method,
      data: options.data,
      header: {
        "content-type": isFormData
          ? "application/x-www-form-urlencoded"
          : "application/json;charset=UTF-8",
        Authorization: token,
        wxToken: token
        // cookie: "JSESSIONID=15302B1F20D0992172E9B26231DDDCA9"
      },
      success(res) {
        resolve(res.data.retData);
      },
      fail(error) {
        reject(error.errMsg);
      }
    });
  });
};

const get = <T extends {}>(url: string, options?: T) => {
  Taro.showLoading()
  return request(url, { method: "GET", data: options });
};
const post = <T extends {}>(url: string, options: T) => {
  // console.log(`${app.globalData.globalUrl}`);
  return request(url, { method: "POST", data: options });
};

const postTimeOut = <T extends {}>(url: string, options: T) => {
  // 有请求超时的检测
  return request(url, { method: "POST", data: options }, false, true);
};

const formDataPost = <T extends {}>(url: string, options: T) => {
  // console.log(`${app.globalData.globalUrl}`);
  return request(url, { method: "POST", data: options }, true);
};

const put = (url: string, options = {}) => {
  return request(url, { method: "PUT", data: options });
};
// 不能声明DELETE（关键字）
const remove = (url: string, options = {}) => {
  return request(url, { method: "DELETE", data: options });
};

export const OriginRequest = {
  request: originRequest
};

export const CustomRequest = {
  request,
  get,
  post,
  postTimeOut,
  formDataPost,
  put,
  remove
};

export const DownLoadFileToTemp = async (fileId: string, ext: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    Taro.downloadFile({
      // url: `${baseUrl}common/attachment/${fileId}`,
      // url: `${baseImageUrl}solar/public/${fileId}.${ext}`, 
      // url: generateImageUrl(fileId, ext),
      url: '',
      header: {
        token: Taro.getStorageSync('token')
      },
      success: function (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          // Taro.playVoice({
          //   filePath: res.tempFilePath
          // })
          resolve(res.tempFilePath)
        }
      },
      fail: function (error) {
        console.log(error)
        reject(error)
      },

    }
    )
  });
}

export interface IDownLoadAttachment {
  id: string
  /**
   * 格式
   */
  ext: string
  name: string
  uuid: string
  size: number
  location: number
}

export const DownLoadFileTransfer = (data: IDownLoadAttachment[]) => {
  const urls = data.map(async (item) => {
    // const url = await DownLoadFileToTemp('2c9180837b6cc1f4017b6d2289320000')
    const url = await DownLoadFileToTemp(item.uuid, item.ext)
    return {
      url,
      ext: item.ext
    }
  })
  return urls
}